package com.bbtShop.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbtShop.config.RequestWrapper;
import com.bbtShop.core.model.SysLoginLog;
import com.bbtShop.core.model.SysMenu;
import com.bbtShop.core.model.UserInfoDto;
import com.bbtShop.core.utils.IpUtil;
import com.bbtShop.core.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.LinkedList;

import static com.bbtShop.core.utils.RedisUtil.fex;

/**
 * @author : manke
 * @Description
 * @Date: 2020/10/31 11:02
 */
@Component
@Slf4j
public class AnnotationParse {
    public final static int flag_no_token= 10001; // 未携带token
    public final static int flag_failed= 10002; // token验证失败
    public final static int flag_no_permission= 10003; //无权限
    public final static int pass=0;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private  HttpServletRequest request;

    public Integer LoginParse(Method method){
        if (method.isAnnotationPresent(Login.class)){
            //验证token
            String token = request.getHeader("token");
            if (token==null||"".equals(token)){
                log.info("=====未携带token");
                return flag_no_token;
            }
            String userInfo = redisUtil.get(fex + token);
            if (userInfo==null||"".equals(userInfo)){
                log.info("=====token验证失败");
                return flag_failed;
            }
            //获取controller 携带的权限标识
            String permission = method.getAnnotation(Login.class).permission();
            if ("".equals(permission)){
                //不验证权限 注解未携带权限标识 只验证是否登录
                log.info("========不验证权限，注解未带权限标识");
                return pass;
            }
            ObjectMapper objectMapper = new ObjectMapper();
            JSONObject jsonObject = JSON.parseObject(userInfo);
            UserInfoDto userInfoDto = objectMapper.convertValue(jsonObject, UserInfoDto.class);
            //验证权限
            if (!userInfoDto.getPermission().contains(permission)){
                return flag_no_permission;
            }
        }
        return pass;
    }
}
